package awesome;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Reads configuration properties from file. 
 * Uses singleton (via enum) so each user class doesn't need its own instance.
 * 
 * @author Chris Carpenter
 * 
 */
public enum ServerConfig {
	INSTANCE; //singleton instance
	
	private String propFile="awesome.properties";
	
	private Properties configProperties;
	{ //init block
		load();
	}
	
	/**
	 * Retrieves property from configuration. If the key is not found, 
	 * the error is logged, and null is returned.
	 * @param key Key of the property to find
	 * @return Property value
	 */
	public String getProperty(String key) {
		String retProp = this.configProperties.getProperty(key);
		if (retProp==null)
			Logger.getLogger("awesome.server").warning(
					"Could not find property: "
					+ key);
		return retProp;
		
	}
	
	/**
	 * Reloads the properties file.
	 * 
	 * Since the key/value pairs are stored in memory, they will not
	 * be updated when the values are changed on disk. Thus, a manual
	 * update is provided.
	 * 
	 * Note that changed values will not nessisarily take immidiate
	 * effect.
	 */
	public void reloadConfig() {
		load();
	}
	
	private void load() {
		try {
			FileInputStream configFile = new FileInputStream(propFile);
			this.configProperties = new Properties();
			this.configProperties.load(configFile);
			configFile.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
